#include "spinlock.h"
#include "log.h"

Spinlock::Spinlock()
{
	int rc;
	if ( (rc = pthread_spin_init(&_spinlock, NULL)) != 0)
	{
		ELOG("pthread_spin_init() failed: %d", rc);
		abort();
	}
}

Spinlock::~Spinlock()
{	
	int rc;
	if ( (rc = pthread_spin_destroy(&_spinlock)) != 0)
	{
		ELOG("pthread_spin_destroy() failed: %d", rc);
		abort();
	}
}

int Spinlock::Lock()
{
	int rc;
	if ( (rc = pthread_spin_lock(&_spinlock)) != 0)
	{
		ELOG("pthread_spin_lock() failed: %d", rc);
		abort();
		return -1;
	}
	return 0;
}

int Spinlock::Unlock()
{
	int rc;
	if ( (rc = pthread_spin_unlock(&_spinlock)) != 0)
	{
		ELOG("pthread_spin_unlock() failed: %d", rc);
		abort();
		return -1;
	}
	return 0;
}

int Spinlock::TryLock()
{
	int rc;
	if ( (rc = pthread_spin_trylock(&_spinlock)) != 0)
	{
		if (rc == EBUSY)
		{
			return 1;
		}
		else
		{
			ELOG("pthread_spin_trylock() failed: %d", rc);
			abort();
			return -1;
		}
	}
	return 0;
}